import { useState } from 'react';
import './Calendar.scss';
import { Select } from 'antd';
import { LeftOutlined, RightOutlined } from '@ant-design/icons';

type DayData = {
    date: number;
    lunar: string;
    month: number;
    isOtherMonth?: boolean;
    events?: { name: string; link?: string }[]; // 改为数组支持多节日
};



// 1. 创建节日数据源
const festivalData = [
    // 中国节日
    { date: "01-01", name: "元旦", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "01-24", name: "小年", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "01-25", name: "除夕", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "01-26", name: "春节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "01-27", name: "初二", link:"https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "01-28", name: "初三", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "02-08", name: "元宵节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html"},
    { date: "04-04", name: "清明节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "05-01", name: "劳动节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "05-04", name: "青年节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "06-05", name: "芒种", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html"},
    { date: "06-07", name: "高考", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "06-08", name: "高考", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "06-11", name: "中国人口日", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },

    { date: "06-25", name: "端午节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
     { date: "07-01", name: "建党节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
        { date: "07-03", name: "小署", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
     { date: "08-01", name: "建军节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "10-01", name: "国庆节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "10-14", name: "重阳节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },

    // 国际节日
    { date: "02-14", name: "情人节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "03-08", name: "妇女节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "04-01", name: "愚人节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "06-01", name: "儿童节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
   
    { date: "06-06", name: "全国爱眼日", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
  

    { date: "06-12", name: "世界无童工日", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "06-14", name: "亲吻情人节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "09-10", name: "教师节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "11-05", name: "世界海啸日", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "11-08", name: "记者日", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "11-09", name: "消防宣传日", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "11-10", name: "世界青年节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "11-11", name: "双11", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "11-14", name: "电影情人节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "11-17", name: "大学生节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "11-21", name: "世界问候日", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "11-28", name: "感恩节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "12-24", name: "平安夜", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
    { date: "12-25", name: "圣诞节", link: "https://www.eqxiu.com/mall/moban/laodongjie-97041.html" },
];

function Calendar() {
    // 当前显示的年月状态
    const [currentDate, setCurrentDate] = useState({
        year: new Date().getFullYear(),
        month: new Date().getMonth() + 1,
        displayMonth: new Date().getMonth() + 1
    });
    // 星期
    const weekDays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
  

    // 处理年份切换
    const handleYearChange = (value: number) => {
        setCurrentDate(prev => ({
            ...prev,
            year: value
        }));
    };

    // 处理月份切换
    const handleMonthChange = (increment: number) => {
        setCurrentDate(prev => {
            let newMonth = prev.month + increment;
            let newYear = prev.year;

            if (newMonth > 12) {
                newMonth = 1;
                newYear++;
            } else if (newMonth < 1) {
                newMonth = 12;
                newYear--;
            }

            return {
                year: newYear,
                month: newMonth,
                displayMonth: newMonth
            };
        });
    };

    // 回到当前月
    const resetToCurrentMonth = () => {
        const today = new Date();
        setCurrentDate({
            year: today.getFullYear(),
            month: today.getMonth() + 1,
            displayMonth: today.getMonth() + 1
        });
    };

    // 处理节日点击
    const handleEventClick = (eventName: string, link?: string) => {
        if (link) {
            window.open(link, '_blank');
        } else {
            alert(`查看 ${eventName} 的详情`);
        }
    };

    // 生成日历数据（根据当前年月动态生成）
    const generateCalendarData = () => {
        // 获取当前月的第一天和最后一天
        const firstDay = new Date(currentDate.year, currentDate.month - 1, 1);
        const lastDay = new Date(currentDate.year, currentDate.month, 0);

        // 计算日历表格数据
        const weeks: DayData[][] = [];
        let currentWeek: DayData[] = [];

        // 填充上个月末尾的几天
        const startDayOfWeek = firstDay.getDay();
        for (let i = 0; i < startDayOfWeek; i++) {
            const date = new Date(currentDate.year, currentDate.month - 1, -startDayOfWeek + i + 1);
            currentWeek.push({
                date: date.getDate(),
                lunar: getLunarDay(date),
                month: currentDate.month - 1 || 12,
                isOtherMonth: true
            });
        }

        // 填充本月
        for (let day = 1; day <= lastDay.getDate(); day++) {
            const date = new Date(currentDate.year, currentDate.month - 1, day);
            const dayData: DayData = {
                date: day,
                lunar: getLunarDay(date),
                month: currentDate.month,
                events: [] // 初始化事件数组
            };

            // 2. 动态匹配节日 - 日期格式 MM-DD
            const month = date.getMonth() + 1;
            const dateStr = `${String(month).padStart(2, '0')}-${String(day).padStart(2, '0')}`;

            // 查找匹配的节日
            const festivals = festivalData.filter(festival => festival.date === dateStr);

            // 添加匹配到的节日
            if (festivals.length > 0) {
                festivals.forEach(festival => {
                    dayData.events!.push({
                        name: festival.name,
                        link: festival.link
                    });
                });
            }

            currentWeek.push(dayData);

            // 周末换行
            if (currentWeek.length === 7) {
                weeks.push(currentWeek);
                currentWeek = [];
            }
        }

        // 填充下个月开始的几天
        if (currentWeek.length > 0) {
            const daysNeeded = 7 - currentWeek.length;
            for (let i = 1; i <= daysNeeded; i++) {
                const date = new Date(currentDate.year, currentDate.month, i);
                currentWeek.push({
                    date: date.getDate(),
                    lunar: getLunarDay(date),
                    month: currentDate.month + 1 > 12 ? 1 : currentDate.month + 1,
                    isOtherMonth: true
                });
            }
            weeks.push(currentWeek);
        }

        return weeks;
    };

    // 简化农历获取
    const getLunarDay = (date: Date): string => {
        const lunarDates = [
            "初一", "初二", "初三", "初四", "初五", "初六", "初七", "初八", "初九", "初十",
            "十一", "十二", "十三", "十四", "十五", "十六", "十七", "十八", "十九", "二十",
            "廿一", "廿二", "廿三", "廿四", "廿五", "廿六", "廿七", "廿八", "廿九", "三十"
        ];
        return lunarDates[(date.getDate() - 1) % lunarDates.length];
    }



    // 动态生成营销事件数据（基于节日数据源）
   const generateMarketingEvents = () => {
    const today = new Date();
    today.setHours(0, 0, 0, 0); // 重置时间为00:00:00
    const currentYear = currentDate.year;

    // 筛选当前月且剩余天数≥0的事件
    const events = festivalData
        .filter(festival => {
            const [monthStr, dayStr] = festival.date.split('-');
            const month = parseInt(monthStr, 10);
            const day = parseInt(dayStr, 10);
            const isCurrentMonth = month === currentDate.month;
            
            if (!isCurrentMonth) return false;
            
            // 计算剩余天数
            const eventDate = new Date(currentYear, month - 1, day);
            eventDate.setHours(0, 0, 0, 0);
            const timeDiff = eventDate.getTime() - today.getTime();
            const daysLeft = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
            
            // 只保留剩余天数≥0的事件
            return daysLeft >= 0;
        })
        .map(festival => {
            const [monthStr, dayStr] = festival.date.split('-');
            const month = parseInt(monthStr, 10);
            const day = parseInt(dayStr, 10);
            
            const eventDate = new Date(currentYear, month - 1, day);
            eventDate.setHours(0, 0, 0, 0);
            const timeDiff = eventDate.getTime() - today.getTime();
            const daysLeft = Math.ceil(timeDiff / (1000 * 60 * 60 * 24));
            
            return {
                ...festival,
                date: `${month}月${String(day).padStart(2, '0')}日`, // 修改这里
                daysLeft,
            };
        });
        
    // 按日期分组（同一天的事件放在一起）
    const groups = events.reduce((acc: Record<string, any[]>, festival) => {
        const date = festival.date;
        if (!acc[date]) {
            acc[date] = [];
        }
        acc[date].push(festival);
        return acc;
    }, {});
    
    // 转换分组数据为数组（返回已经处理好的数组）
    return Object.keys(groups).map(date => ({
        date,
        events: groups[date],
        daysLeft: groups[date][0].daysLeft
    }));
};

    // 生成节日数据
    const marketingEvents = generateMarketingEvents();
    

   

    // 年份选项
    const yearOptions = [
        { value: 2025, label: '2025' },
        { value: 2026, label: '2026' },
        { value: 2027, label: '2027' }
    ];




    // 生成日历数据
    const calendarData = generateCalendarData();

    return (
        <div className="calendar-container">
            {/* 顶部日期显示和切换控件 */}
            <div className="calendar-header">
                <div className="controls-container">
                    <div className="year-selector">
                        <Select
                            value={currentDate.year}
                            onChange={handleYearChange}
                            options={yearOptions}

                            className="year-select"

                        />
                    </div>

                    <div className="month-selector">
                        <button
                            className="month-button prev"
                            onClick={() => handleMonthChange(-1)}
                        >
                            <LeftOutlined />
                        </button>
                        <span className="current-month">{`${currentDate.month}月`}</span>
                        <button
                            className="month-button next"
                            onClick={() => handleMonthChange(1)}
                        >
                            <RightOutlined />
                        </button>
                    </div>

                    <button
                        className="reset-button"
                        onClick={resetToCurrentMonth}
                    >
                        回到本月
                    </button>
                </div>
            </div>

            {/* 主内容区 */}
            <div className="calendar-main">
                {/* 左侧日历 */}
                <div className="calendar-grid">
                    {/* 星期标签 */}
                    <div className="week-header">
                        {weekDays.map((day, index) => (
                            <div key={index} className="week-day">{day}</div>
                        ))}
                    </div>

                    {/* 日期格子 */}
                    {calendarData.map((week, weekIndex) => (
                        <div key={weekIndex} className="week-row">
                            {week.map((day, dayIndex) => (
                                <div
                                    key={dayIndex}
                                    className={`day-cell ${day.isOtherMonth ? 'other-month' : ''}`}
                                >
                                    <div className="solar-date">{day.date}</div>
                                    <div className="lunar-date">{day.lunar}</div>
                                    {day.events && day.events.length > 0 && (
                                        <div className="events-container">
                                            {day.events.slice(0, 2).map((event, idx) => ( // 每个格子最多显示2个事件
                                                <div
                                                    key={idx}
                                                    className="event-marker"
                                                    onClick={() => handleEventClick(event.name, event.link)}
                                                >
                                                    {event.name}
                                                </div>
                                            ))}
                                        </div>
                                    )}
                                </div>
                            ))}
                        </div>
                    ))}
                </div>

                {/* 右侧营销事件 */}
                <div className="marketing-events">
                    <div className="events-title">营销模板直通车</div>
                    <div className="events-list">
                        {marketingEvents.map((group, index) => (
                            <div key={index} className="event-item">
                                <div className="event-header">
                                    <div className="event-date">{group.date}</div>
                                    <div className="event-days">剩<span>{group.daysLeft}</span>天</div>
                                </div>

                                <div className="event-names">
                                    {group.events.map((event, idx) => (
                                        <div
                                            key={idx}
                                            className="event-name"
                                            onClick={() => handleEventClick(event.name, event.link)}
                                        >
                                            {event.name}
                                        </div>
                                    ))}
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
            </div>
        </div>
    );
}

export default Calendar;